import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

import VueLazyLoad from 'vue-lazyload'
Vue.use(VueLazyLoad)
Vue.use(VueLazyLoad, {
  error: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F39%2F24%2F46573cb272478c6.jpg&refer=http%3A%2F%2Fbpic.588ku.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1616864542&t=fd41dc6be75f75c34a6e74ed6111a13a'
})

export default new Vuex.Store({
  state: {
    // cartList: [商品1, 商品2, 商品3]
    cartList: []
  },
  mutations: {
    addCounter(state, payload) {
      payload.count++
    },
    addToCart(state, payload) {
      state.cartList.push(payload)
    },
    checkClick(state, index) {
      state.cartList[index].checked = !state.cartList[index].checked
    }
  },
  actions: {
    addCart(context, payload) {
      return new Promise((resolve, reject) => {
        // repeatCartItem是通过遍历找出的第一个已重复的元素
        const repeatCartItem = context.state.cartList.find((item) => {
          return item.iid === payload.iid
        })
        // 如果存在repeatCartItem值，说明重复，将这个值count+1
        if (repeatCartItem) {
          // repeatCartItem.count += 1
          context.commit('addCounter', repeatCartItem)
          resolve('该商品已存在')
        }
        // 如果不存在repeatCartItem值，将这个元素payload添加到cartList里面
        else {
          // state.cartList.push(payload)
          context.commit('addToCart', payload)
          resolve('已加入购物车')
        }
      })
    }
  },
})
